package de.koller.worlders.engine.tiles.landscape;

import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class OreGeneration {
	
	private final int ore;
	private final int density;
	private final int sizeIterations;
	private static final Random rnd = new Random();
	
	public OreGeneration( int ore, int density, int sizeIterations ) {
		this.ore = ore;
		this.density = density;
		this.sizeIterations = sizeIterations;
	}
	
	public void generate( BufferedImage map ) {
		List<Ore> vein = new ArrayList<>();
		
		for( int i = 0; i < density; i++ ) {
			vein.clear();
			
			vein.add( new Ore( rnd.nextInt( map.getWidth() ), rnd.nextInt( map.getHeight() ) ) );
			for( int s = 0; s < sizeIterations; s++ ) {
				List<Ore> oreAdd = new ArrayList<>();
				for( Ore o : vein ) {
					int d = rnd.nextInt( 4 );
					if( d == 0 ) oreAdd.add( new Ore( o.x+1, o.y ) );
					if( d == 1 ) oreAdd.add( new Ore( o.x-1, o.y ) );
					if( d == 2 ) oreAdd.add( new Ore( o.x, o.y+1 ) );
					if( d == 3 ) oreAdd.add( new Ore( o.x, o.y-1 ) );
				}
				vein.addAll( oreAdd );
			}
			
			for( Ore o : vein ) 
				try {
					map.setRGB( o.x, o.y, ore );
				} catch( ArrayIndexOutOfBoundsException ex ) {
					
				}
		}
	}

	private static class Ore {
		private final int x;
		private final int y;

		public Ore( int x, int y ) {
			this.x = x;
			this.y = y;
		}
	}
	
}
